<!--
 * @Author: 谢小康 2170673706@qq.com
 * @Date: 2023-12-01 14:32:54
 * @LastEditors: 谢小康 2170673706@qq.com
 * @LastEditTime: 2024-01-19 14:09:00
 * @FilePath: \my_bolg_admin\my_admin\src\view\site\links.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <span>友链管理</span>
            </div>
        </template>
        <div>
            <el-form :inline="true" :model="form" class="demo-form-inline">
                <el-form-item label="用户名字">
                    <el-input v-model="form.name" placeholder="输入用户名" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">
                        <el-icon class="el-input__icon mr-2">
                            <search />
                        </el-icon>
                        查询
                    </el-button>
                </el-form-item>
            </el-form>
            <div class=""><el-button type="danger" size="small" :icon="Delete" @click="deletelists($event)">全部删除</el-button>
            </div>
            <el-tabs v-model="activeName" class="demo-tabs" @tab-change="changetab">
                <el-tab-pane label="全部友链" name="allLink">
                    <el-table size="small" ref="multipleTableRef" :data="tableData" style="width: 100%" max-height="380"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="50" />
                        <el-table-column type="index" width="75" label="序号" />
                        <el-table-column label="网站头像" width="100">
                            <template #default="scope">
                                <el-avatar :src="scope.row.avatar" />
                            </template>
                        </el-table-column>
                        <el-table-column property="name" label="网站名字" width="120" />
                        <el-table-column property="description" label="网站描述" width="150" />
                        <el-table-column property="address" label="网站地址" width="180" />
                        <el-table-column property="applyTime" label="申请日期" width="120" />
                        <el-table-column property="accessTime" label="通过日期" width="120" />
                        <el-table-column fixed="right" label="选项" width="120">
                            <template #default="scope">
                                <el-button link type="danger" size="small" @click="handledelete(scope.row)">删除</el-button>
                                <dialogg :istoshow="showadd" title="提示" @cansol="cansol('删除')" width="20%">
                                    <template #body>
                                        <span>确定要删除?</span>
                                    </template>
                                    <template #footer>
                                        <span class="dialog-footer">
                                            <el-button @click="cansol('提示')">取消</el-button>
                                            <el-button type="danger" @click="subandclose('删除')">
                                                确定
                                            </el-button>
                                        </span>
                                    </template>
                                </dialogg>
                                <el-button link type="primary" size="small" @click="handleemit(scope.row)">编辑</el-button>
                                <dialogg :istoshow="showemit" title="编辑" @cansol="cansol('编辑')" width="30%">
                                    <template #body>
                                        <el-form :model="updatalinks" label-width="80px">
                                            <el-form-item label="网站名称:">
                                                <el-input v-model="updatalinks.name" />
                                            </el-form-item>
                                            <el-form-item label="网站描述:">
                                                <el-input v-model="updatalinks.description" />
                                            </el-form-item>
                                            <el-form-item label="网站地址:">
                                                <el-input v-model="updatalinks.address" />
                                            </el-form-item>
                                            <el-form-item label="网站头像:">
                                                <upload :limit="1" :multiple="true" :height="100" :width="100"
                                                    v-model:imglist="updatalinks.avatar"></upload>
                                            </el-form-item>
                                        </el-form>
                                    </template>
                                    <template #footer>
                                        <span class="dialog-footer">
                                            <el-button @click="cansol('编辑')">取消</el-button>
                                            <el-button type="primary" @click="subandclose('编辑')">
                                                确定
                                            </el-button>
                                        </span>
                                    </template>
                                </dialogg>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="待审核" name="witLink">
                    <el-table size="small" ref="multipleTableRef" :data="tableData" style="width: 100%" max-height="380"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="50" />
                        <el-table-column type="index" width="75" label="序号" />
                        <el-table-column label="网站头像" width="100">
                            <template #default="scope">
                                <el-avatar :src="scope.row.avatar" />
                            </template>
                        </el-table-column>
                        <el-table-column property="name" label="网站名字" width="100" />
                        <el-table-column property="description" label="网站描述" width="120" />
                        <el-table-column property="address" label="网站地址" width="150" />
                        <el-table-column property="note" label="备注" width="100" />
                        <el-table-column property="applyTime" label="申请日期" width="120" />
                        <el-table-column property="accessTime" label="通过日期" width="120" />
                        <el-table-column fixed="right" label="选项" width="120">
                            <template #default="scope">
                                <el-button link type="danger" size="small" @click="Auditfriend(scope.row)">审核</el-button>
                                <dialogg :istoshow="showaudit" title="审核" @cansol="cansol('审核')" width="30%">
                                    <template #body>
                                        <el-form :model="auditdata" label-width="80px">
                                            <el-form-item label="网站名称:">
                                                <el-text class="mx-1" type="primary">{{ auditdata.name }}</el-text>
                                            </el-form-item>
                                            <el-form-item label="网站描述:">
                                                <el-text class="mx-1" type="primary">{{ auditdata.description }}</el-text>
                                            </el-form-item>
                                            <el-form-item label="网站地址:">
                                                <el-text class="mx-1" type="primary">{{ auditdata.address }}</el-text>
                                            </el-form-item>
                                            <el-form-item label="备注:">
                                                <el-text class="mx-1" type="primary">{{ auditdata.note }}</el-text>
                                            </el-form-item>
                                            <el-form-item label="网站头像:">
                                                <el-avatar size="" :src="auditdata.avatar" />
                                            </el-form-item>
                                        </el-form>
                                    </template>
                                    <template #footer>
                                        <span class="dialog-footer">
                                            <el-button><a ref="aLink" :href="auditdata.address">走访</a></el-button>
                                            <el-button type="primary" @click="audit(2)">
                                                不过
                                            </el-button>
                                            <el-button type="primary" @click="audit(1)">
                                                通过
                                            </el-button>
                                        </span>
                                    </template>
                                </dialogg>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
            <pagination :currentPage="allcurrentPage" :pageSize="allpageSize" :total="alltotal" @updatepage="Allchangepage">
            </pagination>
        </div>
    </el-card>
</template>

<script setup>
import moment from 'moment';
import { onMounted, reactive, ref, inject, watch } from 'vue'
import dialogg from '@/components/dialog.vue';
import pagination from '@/components/pagination.vue';
import {
    Search,
    Delete
} from '@element-plus/icons-vue'
import { getfriends, getgountfrient, auditFriends, searchfriend, deleteFriend, updatelinks, deleteimg } from "@/api/friend.js"
import upload from "@/components/upload.vue"
import { deepClone } from "@/util/index.js"
import { getQiniuToken } from "@/api/users.js"
import { useBaseStore } from "@/store/Base.js"
import { uploadqiniu, randomString } from "@/util/index.js"
let aLink = ref()
let reload = inject('reload')
const activeName = ref('allLink')
let showadd = ref(false);
let showemit = ref(false)
let showaudit = ref(false)
let baseStore = useBaseStore()
let deletelist = ref()
let corver
/* 表格数据 */
let tableData = ref([
    {
        id: "01",
        applyTime: '2016-05-03',
        accessTime: '2016-05-03',
        name: 'Tom',
        address: 'https://cube.elemecdn.com/',
        description: "打车擦上次打发的车",
        avatar: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
        note:""
    },

])
/* 编辑友链的数据 */
let updatalinks = ref({
    name: "",
    description: "",
    address: "",
    avatar: []
})
/* 审核的数据 */
let auditdata = reactive({
    name: "",
    description: "",
    address: "",
    avatar: "",
    note:"",
    id: 0,
})
/* 审核提交 */
async function audit(fleg) {
    let res = await auditFriends({
        fleg: fleg,
        id: auditdata.id
    })
    if (res.data.status == 200) {
        ElMessage({
            message: '审核完成',
            type: 'success',
        })
        reset("审核")
       
    } else {
        ElMessage({
            message: '出错了',
            type: 'warning',
        })
    }
    reload()
}
function reset(data) {
    if (data == "审核") {
        auditdata.name = ""
        auditdata.description = ""
        auditdata.address = ""
        auditdata.avatar = ""
        auditdata.id = 0
        auditdata.note=""
        showaudit.value = false
    } else if (data == "编辑") {
        updatalinks.value.name = ""
        updatalinks.value.description = ""
        updatalinks.value.address = ""
        updatalinks.value.avatar = ""
        showemit.value = false
    }
}
let allcurrentPage = ref(1)
let allpageSize = ref(5)
let alltotal = ref()
let tempcurrentpage = ref()
/* 修改页码 */
async function Allchangepage(val) {
    allcurrentPage.value = val;
    if (iszhefirstSerch.value) {
        if (activeName.value == "witLink") {
            await getdata(2)
        } else {
            await getdata(1)
        }
    } else {
        await serchfun()
    }
}
/* 改变 */
async function changetab(name) {
    allcurrentPage.value = 1;
    tableData.value = [];
    if (iszhefirstSerch.value) {
        if (activeName.value == "witLink") {
            await getdata(2)
        } else {
            await getdata(1)
        }
    } else {
        await serchfun()
    }
}
/* 审核 */
function Auditfriend(data) {
    showaudit.value = true;
    auditdata.address = data.address
    auditdata.name = data.name
    auditdata.description = data.description
    auditdata.avatar = data.avatar
    auditdata.id = data.id
    auditdata.note = data.note
}
onMounted(async () => {
    await getdata(1)
})
/* 获取数据 */
async function getdata(friend_status) {
    let res = getfriends({
        page: allcurrentPage.value,
        pageSize: allpageSize.value,
        friend_status
    })
    let ress = getgountfrient({
        friend_status
    })
    let resss = await Promise.all([res, ress])
    alltotal.value = resss[1].data.data
    if (resss[0].data.status == 200) {
        tableData.value = resss[0].data.data.map(item => {
            return {
                id: item.id,
                applyTime: moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
                accessTime: moment(item.updatedAt).format('YYYY-MM-DD HH:mm:ss'),
                name: item.friend_name,
                address: item.friend_url,
                description: item.friend_sign,
                avatar: item.friend_corver,
                note: item.friend_note,
            }
        })
    } else {
        ElMessage({
            message: '暂无数据',
            type: 'warning',
        })
    }
}
/* 删除 */
const handleSelectionChange = async (val) => {
    deletelist.value = val
}
let deleteinfo = {}
function handledelete(data) {
    deleteinfo = deepClone(data)
    showadd.value = true
}
async function deletelists(e, friendlist) {
    if (!friendlist) {
        friendlist = deletelist.value
    }
    let res = await deleteFriend({ friendlist })
    if (res.data.status == 200) {
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
        
    } else {
        ElMessage({
            message: '删除失败',
            type: 'warning',
        })
    }
    reload()
}
function handleemit(row) {
    updatalinks.value = deepClone(row)
    corver = row.avatar
    updatalinks.value.avatar = [{
        url: row.avatar,
        name: row.avatar
    }]
    showemit.value = true
}
/* 取消 */
function cansol(option) {
    if (option == "编辑") {
        showemit.value = false
    } else if (option == "删除") {
        showadd.value = false;
    } else {
        showaudit.value = false
    }

}
async function subandclose(option, row) {
    if (option == "编辑") {
        /* 先上传图片 */
        let data = await getQiniuToken();
        /* 获取七牛云的token成功 */
        if (data.data.status == 200) {
            baseStore.qiniuToken = data.data.data.uploadToken;
            let ress = await uploadqiniu(updatalinks.value.avatar);
            let newimg = ""
            if (ress.length !== 0) {
                newimg = import.meta.env.VITE_API_PHOTO + ress[0].data.key
                let result = await deleteimg({
                    oldimg: corver.split("/").pop(),
                })
            }
            let pramsdata = {
                friend_url: updatalinks.value.address,
                friend_corver: newimg ? newimg : corver,
                friend_sign: updatalinks.value.description,
                friend_name: updatalinks.value.name
            }
            let res = await updatelinks({ data: pramsdata, id: updatalinks.value.id })
            if (res.data.status == 200) {
                ElMessage.success("修改成功")
                showemit.value = false
                reset("编辑")
            }
            reload()

        }
        showemit.value = false
    } else if (option == "删除") {
        await deletelists("", [deleteinfo])
        deleteinfo = {}
        showadd.value = false;
        reload()
    }
}

let form = ref({
    name: ''
})
let iszhefirstSerch = ref(true)
async function onSubmit() {
    /* 查询为空 */
    if (form.value.name == '') {
        ElMessage({
            message: '不能为空',
            type: 'warning',
        })
    } else {
        tableData.value = []
        if (iszhefirstSerch.value) {
            tempcurrentpage.value = allcurrentPage.value
            allcurrentPage.value = 1
            iszhefirstSerch.value = false
        } else {
            allcurrentPage.value = 1
        }
        await serchfun()
    }
}
async function serchfun() {
    let fleg = 1
    if (activeName.value == "witLink") {
        fleg = 2
    }
    let res = await searchfriend({
        fleg,
        keyword: form.value.name,
        page: allcurrentPage.value,
        pageSize: allpageSize.value
    })
    if (res.data.status == 200) {
        tableData.value = res.data.data.list.map(item => {
            return {
                id: item.id,
                applyTime: moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
                accessTime: moment(item.updatedAt).format('YYYY-MM-DD HH:mm:ss'),
                name: item.friend_name,
                address: item.friend_url,
                description: item.friend_sign,
                avatar: item.friend_corver
            }
        })
        alltotal.value = res.data.data.total
    } else {
        ElMessage({
            message: '搜索失败',
            type: 'warning',
        })
    }
}
watch(() => form.value.name, async (newval, oldval) => {
    if (newval == '') {
        iszhefirstSerch.value = true
        allcurrentPage.value = tempcurrentpage.value
        if (activeName.value == "witLink") {
            await getdata(2)
        } else {
            await getdata(1)
        }
    }
    if (newval !== '' && oldval.length > newval.length) {
        iszhefirstSerch.value = false
        allcurrentPage.value = 1
        await serchfun()
    }
})
</script>

<style lang="css" scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

:deep(.el-card__header) {
    padding: 5px 25px !important;
}
</style>